<!DOCTYPE html>
<html>
<head><meta name="generator" content="Hexo 3.8.0">
    

    

    



    <meta charset="utf-8">
    
    
    
    
    <title>mpvue-vue-socketio使用实现即时通讯 | lafen | lafen&#39;s personal blog</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="mpvue,vue,socket.io">
    <meta name="description" content="前言实现微信小程序与后台管理系统的聊天对话，信息类型包括文本、图片、语音，因为后台服务开发也是使用的socket.io，因此前端部分也采用这种更成熟的方案socket.io。得益于他的底层Engine.io实现，他支持任何浏览器与移动设备。（Engine.io建立在长轮询基础之上，连接成功之后，可根据运行环境支持情况切换不同的连接方式，像是一个适配器） 简单介绍从socket.io的github介">
<meta name="keywords" content="mpvue,vue,socket.io">
<meta property="og:type" content="article">
<meta property="og:title" content="mpvue-vue-socketio使用实现即时通讯">
<meta property="og:url" content="https://lafen.gitee.io/2019/10/15/mpvue-vue-socketio使用实现即时通讯/mpvue-vue-socketio使用实现即时通讯/index.html">
<meta property="og:site_name" content="lafen">
<meta property="og:description" content="前言实现微信小程序与后台管理系统的聊天对话，信息类型包括文本、图片、语音，因为后台服务开发也是使用的socket.io，因此前端部分也采用这种更成熟的方案socket.io。得益于他的底层Engine.io实现，他支持任何浏览器与移动设备。（Engine.io建立在长轮询基础之上，连接成功之后，可根据运行环境支持情况切换不同的连接方式，像是一个适配器） 简单介绍从socket.io的github介">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://i.loli.net/2019/10/15/F4EPrN5wYytuBJA.png">
<meta property="og:image" content="https://i.loli.net/2019/10/18/tADCTIGWRsKZlvO.png">
<meta property="og:image" content="https://i.loli.net/2019/10/15/hndSFIZOvLlY4a2.png">
<meta property="og:image" content="https://i.loli.net/2019/10/15/bAiF7LkcVyruCdP.png">
<meta property="og:image" content="https://i.loli.net/2019/10/15/hndSFIZOvLlY4a2.png">
<meta property="og:image" content="https://i.loli.net/2019/12/11/hl2qgjcYNZJyKwF.gif">
<meta property="og:updated_time" content="2019-12-11T02:38:33.971Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="mpvue-vue-socketio使用实现即时通讯">
<meta name="twitter:description" content="前言实现微信小程序与后台管理系统的聊天对话，信息类型包括文本、图片、语音，因为后台服务开发也是使用的socket.io，因此前端部分也采用这种更成熟的方案socket.io。得益于他的底层Engine.io实现，他支持任何浏览器与移动设备。（Engine.io建立在长轮询基础之上，连接成功之后，可根据运行环境支持情况切换不同的连接方式，像是一个适配器） 简单介绍从socket.io的github介">
<meta name="twitter:image" content="https://i.loli.net/2019/10/15/F4EPrN5wYytuBJA.png">
    
        <link rel="alternate" type="application/atom+xml" title="lafen" href="/atom.xml">
    
    <link rel="shortcut icon" href="/img/favicon.ico">
    <link rel="stylesheet" href="//unpkg.com/hexo-theme-material-indigo@latest/css/style.css">
    <script>window.lazyScripts=[]</script>

    <!-- custom head -->
    

</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide">
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" style="background-image:url(/img/brand.jpg)">
      <div class="brand">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="/img/avatar.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">lafen</h5>
          <a href="mailto:1031822863@qq.com" title="1031822863@qq.com" class="mail">1031822863@qq.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/">
                <i class="icon icon-lg icon-home"></i>
                home
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/archives">
                <i class="icon icon-lg icon-archives"></i>
                Archives
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/tags">
                <i class="icon icon-lg icon-tags"></i>
                Tags
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/categories">
                <i class="icon icon-lg icon-th-list"></i>
                Categories
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://github.com/zhongxiaotian" target="_blank">
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="http://www.weibo.com/" target="_blank">
                <i class="icon icon-lg icon-weibo"></i>
                Weibo
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://gitee.com/lafen" target="_blank">
                <i class="icon icon-lg icon-link"></i>
                Gitee
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">mpvue-vue-socketio使用实现即时通讯</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">mpvue-vue-socketio使用实现即时通讯</h1>
        <h5 class="subtitle">
            
                <time datetime="2019-10-15T10:12:46.000Z" itemprop="datePublished" class="page-time">
  2019-10-15
</time>


	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/mpvue/">mpvue</a><ul class="article-category-list-child"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/mpvue/vue/">vue</a><ul class="article-category-list-child"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/mpvue/vue/socket-io/">socket.io</a></li></ul></li></ul></li></ul>

            
        </h5>
    </div>

    


</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap post-toc-shrink" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#前言"><span class="post-toc-number">1.</span> <span class="post-toc-text">前言</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#简单介绍"><span class="post-toc-number">2.</span> <span class="post-toc-text">简单介绍</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#连接方式"><span class="post-toc-number">3.</span> <span class="post-toc-text">连接方式</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Vue中使用"><span class="post-toc-number">4.</span> <span class="post-toc-text">Vue中使用</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#小程序中使用"><span class="post-toc-number">5.</span> <span class="post-toc-text">小程序中使用</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#最后"><span class="post-toc-number">6.</span> <span class="post-toc-text">最后</span></a></li></ol>
        </nav>
    </aside>


<article id="post-mpvue-vue-socketio使用实现即时通讯/mpvue-vue-socketio使用实现即时通讯" class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">mpvue-vue-socketio使用实现即时通讯</h1>
        <div class="post-meta">
            <time class="post-time" title="2019-10-15 18:12:46" datetime="2019-10-15T10:12:46.000Z" itemprop="datePublished">2019-10-15</time>

            
	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/mpvue/">mpvue</a><ul class="article-category-list-child"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/mpvue/vue/">vue</a><ul class="article-category-list-child"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/mpvue/vue/socket-io/">socket.io</a></li></ul></li></ul></li></ul>



            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style="display:none">
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>实现微信小程序与后台管理系统的聊天对话，信息类型包括<strong>文本、图片、语音</strong>，因为后台服务开发也是使用的<code>socket.io</code>，因此前端部分也采用这种更成熟的方案<a href="https://socket.io" target="_blank" rel="noopener">socket.io</a>。得益于他的底层<code>Engine.io</code>实现，他支持任何浏览器与移动设备。（<code>Engine.io</code>建立在<strong>长轮询</strong>基础之上，连接成功之后，可根据运行环境支持情况切换不同的连接方式，像是一个适配器）</p>
<h3 id="简单介绍"><a href="#简单介绍" class="headerlink" title="简单介绍"></a>简单介绍</h3><p>从<code>socket.io</code>的<a href="https://github.com/socketio/socket.io" target="_blank" rel="noopener">github</a>介绍可知，<code>socket.io</code>具有非常多的特点</p>
<table>
<thead>
<tr>
<th style="text-align:left">特点</th>
<th style="text-align:left">描述</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">可靠性</td>
<td style="text-align:left">依赖于<code>Engine.io</code>，支持<code>6</code>种连接方式，可根据宿主环境不同进行切换</td>
</tr>
<tr>
<td style="text-align:left">自动连接</td>
<td style="text-align:left">断开的连接将自动重连，除非你阻止他自动重连</td>
</tr>
<tr>
<td style="text-align:left">断线检测</td>
<td style="text-align:left">服务器和应用都可以知道另一方是否还在线</td>
</tr>
<tr>
<td style="text-align:left">二进制</td>
<td style="text-align:left">在浏览器中 <code>ArraBuffer</code> 和 <code>Blob</code>，<code>Node.js</code> 中支持 <code>ArrayBuffer</code> 和 <code>Buffer</code></td>
</tr>
<tr>
<td style="text-align:left"><code>api</code></td>
<td style="text-align:left">直接通过注册事件形式进行事件监听，发射事件进行事件触发，使用简单</td>
</tr>
<tr>
<td style="text-align:left">跨浏览器</td>
<td style="text-align:left">支持所有主流浏览器，包括移动端</td>
</tr>
<tr>
<td style="text-align:left">多路传输</td>
<td style="text-align:left">基于相同的基础连接，允许通过命名空间创建多路传输</td>
</tr>
<tr>
<td style="text-align:left">聊天室</td>
<td style="text-align:left">支持群发</td>
</tr>
</tbody>
</table>
<p>文档中特点强调了<code>socket.io</code>不是<code>websocket</code>的实现，但<code>socket.io</code>可能会使用<code>websocket</code>进行连接，这主要取决于运行的环境是否支持。</p>
<h3 id="连接方式"><a href="#连接方式" class="headerlink" title="连接方式"></a>连接方式</h3><p><code>socket.io</code>首先会通过<strong>长轮询</strong>连接，连接成功之后会尝试进行协议升级成更可靠稳定的<code>websocket</code>连接方式，如果浏览器支持<code>websocket</code>连接，请求会在请求头中带上<code>Connection:Upgrade</code>、<code>Upgrade:websocket</code>字段，服务器识别该<code>header</code>之后，会将协议升级成<code>websocket</code>连接，后续通信不再依赖<code>http</code>请求。</p>
<p>如果浏览器不支持<code>websocket</code>连接，则会将连接协议降级为长轮询等方式，以提供更简便通用的解决办法，以下是<code>socket.io</code>支持的连接方式：</p>
<ul>
<li><code>WebSocket</code> </li>
<li><code>Flash Socket</code> </li>
<li><code>AJAX long-polling</code> </li>
<li><code>AJAX multipart streaming</code> </li>
<li><code>Forever IFrame</code> </li>
<li><code>JSONP polling</code> </li>
</ul>
<h3 id="Vue中使用"><a href="#Vue中使用" class="headerlink" title="Vue中使用"></a>Vue中使用</h3><p>后台管理系统中基于<code>Vue.js</code>进行，故使用<a href="https://github.com/MetinSeylan/Vue-Socket.io" target="_blank" rel="noopener">vue-socket.io</a>，与<code>socket.io</code>的使用一致</p>
<ol>
<li><strong>npm下载</strong></li>
</ol>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install vue-socket.io</span><br></pre></td></tr></table></figure>
<ol start="2">
<li><strong>全局引入并注册</strong> </li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// main.js</span></span><br><span class="line"><span class="keyword">import</span> VueSocketIO <span class="keyword">from</span> <span class="string">'vue-socket.io'</span></span><br><span class="line"></span><br><span class="line">Vue.use(<span class="keyword">new</span> VueSocketIO(&#123;</span><br><span class="line">  debug: <span class="literal">true</span>,</span><br><span class="line">  connection: <span class="string">'wss://dev.xxx.com'</span>, <span class="comment">// 你的wss地址，小程序必须wss</span></span><br><span class="line">  <span class="comment">// path是后端规定的path路径，query也是后端规定带的参数</span></span><br><span class="line">  options: &#123; <span class="attr">path</span>: <span class="string">'/chat'</span>, <span class="attr">query</span>: QUERY, <span class="attr">transports</span>: [<span class="string">'websocket'</span>], <span class="attr">autoConnect</span>: <span class="literal">false</span> &#125;, <span class="comment">// transports指定连接升级为websocket，不进行默认连接</span></span><br><span class="line">  <span class="comment">// 配合vuex</span></span><br><span class="line">  vuex: &#123;</span><br><span class="line">    store,</span><br><span class="line">    actionPrefix: <span class="string">'socket_'</span>,</span><br><span class="line">    mutationPrefix: <span class="string">'SOCKET_'</span>,</span><br><span class="line">    options: &#123;</span><br><span class="line">      useConnectionNamespace: <span class="literal">true</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;))</span><br></pre></td></tr></table></figure>
<ol start="3">
<li><strong>页面中使用</strong></li>
</ol>
<p>我在<code>mounted</code>中进行连接，在<code>destroyed</code>中断开连接</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// index.vue</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">  <span class="comment">// 开启websocket连接</span></span><br><span class="line">  mounted() &#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.$socket) &#123;</span><br><span class="line">      <span class="keyword">this</span>.$socket.open()</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 断开websocket连接</span></span><br><span class="line">  destroyed() &#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.$socket) &#123;</span><br><span class="line">      <span class="keyword">this</span>.$socket.close()</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">// 注册事件</span></span><br><span class="line">  sockets: &#123;</span><br><span class="line">    <span class="comment">// 直接注册事件，后台服务器会通过事件名触发客户端相应的事件</span></span><br><span class="line">    <span class="comment">// online 、 offline 、message 为后端服务器自定义的事件，由后端主动触发</span></span><br><span class="line">    online(user) &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">'--------online------'</span>)</span><br><span class="line">      <span class="comment">// this.$notify(&#123;</span></span><br><span class="line">      <span class="comment">//   title: '上线通知',</span></span><br><span class="line">      <span class="comment">//   message: `用户 $&#123;user.user_name&#125; 已上线`,</span></span><br><span class="line">      <span class="comment">//   type: 'success',</span></span><br><span class="line">      <span class="comment">//   duration: 2000</span></span><br><span class="line">      <span class="comment">// &#125;)</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment">// 后端定义的触发事件，离线提醒</span></span><br><span class="line">    offline(user) &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">'--------offline------'</span>)</span><br><span class="line">      <span class="comment">// this.$notify(&#123;</span></span><br><span class="line">      <span class="comment">//   title: '下线通知',</span></span><br><span class="line">      <span class="comment">//   message: `用户 $&#123;user.user_name&#125; 已下线`,</span></span><br><span class="line">      <span class="comment">//   type: 'info',</span></span><br><span class="line">      <span class="comment">//   duration: 2000</span></span><br><span class="line">      <span class="comment">// &#125;)</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment">// 后端定义的触发事件，有消息到来</span></span><br><span class="line">    message(data) &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">'---------message------'</span>, data)</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment">// 撤回消息事件，由服务端触发</span></span><br><span class="line">    recallMessage(data) &#123;</span><br><span class="line">      <span class="comment">// console.log(msgId)</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment">// 以下为socket.io提供的事件，同样不需要自己触发，由socket.io自动触发</span></span><br><span class="line">    <span class="comment">// 连接成功后，socket.io会触发此事件</span></span><br><span class="line">    connect() &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">'---------socket connected------'</span>)</span><br><span class="line">      <span class="keyword">this</span>.$message(&#123;</span><br><span class="line">        message: <span class="string">'连接成功！'</span>,</span><br><span class="line">        type: <span class="string">'success'</span></span><br><span class="line">      &#125;)</span><br><span class="line">    &#125;,</span><br><span class="line">    disconnect(reason) &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">'-------socket 断开连接了！'</span>, reason)</span><br><span class="line">      <span class="keyword">this</span>.$message(&#123;</span><br><span class="line">        message: <span class="string">'连接已断开！'</span>,</span><br><span class="line">        type: <span class="string">'error'</span></span><br><span class="line">      &#125;)</span><br><span class="line">    &#125;,</span><br><span class="line">    connect_error(error) &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">'-----socket connect_error----'</span>, error)</span><br><span class="line">    &#125;,</span><br><span class="line">    connect_timeout(timeout) &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">'-----socket connect_timeout----'</span>, timeout)</span><br><span class="line">    &#125;,</span><br><span class="line">    error(error) &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">'-----socket error----'</span>, error)</span><br><span class="line">    &#125;,</span><br><span class="line">    reconnect_attempt(attemptNumber) &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">'-----socket reconnect_attempt ----'</span>, attemptNumber)</span><br><span class="line">    &#125;,</span><br><span class="line">    reconnect(attemptNumber) &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">'-----socket reconnect ----'</span>, attemptNumber)</span><br><span class="line">    &#125;,</span><br><span class="line">    reconnecting(attemptNumber) &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">'-----socket reconnecting ----'</span>, attemptNumber)</span><br><span class="line">    &#125;,</span><br><span class="line">    reconnect_error(error) &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">'-----socket reconnect_error ----'</span>, error)</span><br><span class="line">    &#125;,</span><br><span class="line">    reconnect_failed() &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">'-----socket reconnect_failed ----'</span>)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>那前端如果主动触发服务端的事件呢，也很简单，就通过<code>emit</code>触发即可</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// index.vue</span></span><br><span class="line">methods: &#123;</span><br><span class="line">    <span class="comment">// 发送消息</span></span><br><span class="line">    sendMessage(data) &#123;</span><br><span class="line">        <span class="keyword">const</span> msg = data.value <span class="comment">// 拼接你的数据</span></span><br><span class="line">        <span class="keyword">this</span>.$socket.emit(<span class="string">'message'</span>, msg) <span class="comment">// 这里触发的是服务端的message事件，事件名称自定义</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment">// 撤回，由客户端触发服务端的事件</span></span><br><span class="line">    handleRecallMsg(data) &#123;</span><br><span class="line">      <span class="keyword">this</span>.$socket.emit(<span class="string">'recallMessage'</span>, data)</span><br><span class="line">    &#125;,</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>发送<code>msg</code>格式，消息的格式跟后端商量定义好就行</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> chatObj = &#123;</span><br><span class="line">	<span class="keyword">from</span>: <span class="keyword">this</span>.from_id, <span class="comment">// 从谁发出</span></span><br><span class="line">	to: <span class="keyword">this</span>.to_id,     <span class="comment">// 发给谁</span></span><br><span class="line">	group_chat: <span class="literal">false</span>,  <span class="comment">// 是否群聊里</span></span><br><span class="line">	sender_type: <span class="string">'admin'</span>, <span class="comment">// 发送人角色</span></span><br><span class="line">	content_type: <span class="string">'text'</span>, <span class="comment">// 发送的内容类型，text | image | audio ，语音只在小程序端实现</span></span><br><span class="line">	content: <span class="keyword">this</span>.contentValue, <span class="comment">// 发送的内容</span></span><br><span class="line">	created_at: formatDateTime(<span class="keyword">new</span> <span class="built_in">Date</span>()) <span class="comment">// 时间</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="4">
<li><strong>消息的存储管理</strong></li>
</ol>
<p>关于消息的储存管理这一块，我没有想到比较好的方式，故采用了<code>vuex</code>来进行管理，在<code>vuex</code>使用数组进行消息的管理，实际上，人数多的时候会容易造成卡顿，这部分待完善优化，就不细讲了</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> state = &#123;</span><br><span class="line">  has_off_message: <span class="number">0</span>, <span class="comment">// 是否有离线消息 1 有， 0 无</span></span><br><span class="line">  all_user: [], <span class="comment">// 所有用户聊天列表</span></span><br><span class="line">  all_user_sorted: [], <span class="comment">// 所有用户-排序</span></span><br><span class="line">  current_user: &#123;&#125;, <span class="comment">// 当前用户信息</span></span><br><span class="line">  current_chat: [], <span class="comment">// 当前用户聊天</span></span><br><span class="line">  current_list: [], <span class="comment">// 当前正在聊天的用户列表 -- 即聊天一栏</span></span><br><span class="line">  all_chat_list: [] <span class="comment">// 所有用户聊天</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="5">
<li><strong>实现的功能</strong></li>
</ol>
<ul>
<li>后台管理系统<ul>
<li>分为正在聊天、所有好友两个列表，点击切换好友进行聊天</li>
<li>支持上线、离线提示，支持<strong>离线留言</strong>，离线消息提醒</li>
<li>来信好友自动提升至聊天列表<strong>顶部</strong>，并显示<strong>最近</strong>一条消息</li>
<li>所有好友列表按名字<strong>排序</strong></li>
<li>支持用户名、<code>id</code><strong>搜索好友</strong>，点击可直接开启对话框进行聊天</li>
<li>一键查看好友的所有已填写的信息</li>
<li>支持发送<strong>文本、图片</strong>消息，消息支持<strong>撤回</strong>，可接收<strong>文本、图片、语音</strong>消息</li>
<li>支持滚动加载更多<strong>历史消息</strong>，最近<strong>聊天列表</strong>服务端缓存</li>
<li>支持图片<strong>全屏预览</strong>（<code>v-img</code>）</li>
</ul>
</li>
<li>新加功能<ul>
<li>支持<strong>好友分组</strong>，右键选择分组可将好友添加至分组，新建分组、删除分组，选择分组进行群发消息，分组列表中点击好友可跳转至聊天页面聊天</li>
</ul>
</li>
</ul>
<ol start="6">
<li><strong>实现的效果</strong></li>
</ol>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="https://i.loli.net/2019/10/15/F4EPrN5wYytuBJA.png" alt="im-client.png" title="">
                </div>
                <div class="image-caption">im-client.png</div>
            </figure>
<ol start="7">
<li><strong>新加功能</strong></li>
</ol>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="https://i.loli.net/2019/10/18/tADCTIGWRsKZlvO.png" alt="im-client-new.png" title="">
                </div>
                <div class="image-caption">im-client-new.png</div>
            </figure>
<p>看得出，实现的样式比较丑0.0…</p>
<p><img src="https://i.loli.net/2019/10/15/hndSFIZOvLlY4a2.png" alt="old-luo.png" style="zoom:150%;"></p>
<h3 id="小程序中使用"><a href="#小程序中使用" class="headerlink" title="小程序中使用"></a>小程序中使用</h3><p>微信小程序中，我使用的<code>mpvue</code>进行开发，直接下载包<code>weapp.socket.io</code>，基于<code>socket.io</code>的微信小程序版，所以使用起来也是大同小异</p>
<ol>
<li><strong>npm下载</strong></li>
</ol>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install weapp.socket.io</span><br></pre></td></tr></table></figure>
<ol start="2">
<li><strong>页面中引入使用</strong></li>
</ol>
<p>在<code>onLoad</code>中进行初始化连接，<code>onUnload</code>中断开连接</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// index.vue</span></span><br><span class="line"><span class="keyword">import</span> io <span class="keyword">from</span> <span class="string">'weapp.socket.io'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">    onLoad() &#123;</span><br><span class="line">        <span class="comment">// 初始化连接</span></span><br><span class="line">        <span class="keyword">this</span>.initSocket()</span><br><span class="line">    &#125;,</span><br><span class="line">    onUnload() &#123;</span><br><span class="line">        <span class="comment">// 断开连接</span></span><br><span class="line">        <span class="keyword">this</span>.socketStop()</span><br><span class="line">    &#125;,</span><br><span class="line">    methods: &#123;</span><br><span class="line">        initSocket() &#123;</span><br><span class="line">            <span class="comment">// 是否已连接过</span></span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span>.socket) &#123;</span><br><span class="line">                <span class="keyword">let</span> socket = <span class="keyword">this</span>.socket</span><br><span class="line">                <span class="keyword">return</span></span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 建立socket连接，wss地址、path、query由后端视情况而定</span></span><br><span class="line">            <span class="keyword">let</span> socket = (<span class="keyword">this</span>.socket = io(WSSURL, &#123; <span class="attr">path</span>: PATH, <span class="attr">query</span>: QUERY &#125;))</span><br><span class="line">            <span class="comment">// 开始注册事件</span></span><br><span class="line">            socket.on(<span class="string">'online'</span>, user =&gt; &#123; <span class="built_in">console</span>.log(<span class="string">'自定义事件--上线'</span>, user) &#125;)</span><br><span class="line">            socket.on(<span class="string">'offline'</span>, user =&gt; &#123; <span class="built_in">console</span>.log(<span class="string">'自定义事件--离线'</span>, user) &#125;)</span><br><span class="line">            <span class="comment">// 接收消息</span></span><br><span class="line">            socket.on(<span class="string">'message'</span>, data =&gt; &#123; <span class="built_in">console</span>.log(<span class="string">'服务器返回数据--&gt;'</span>, data) &#125;)</span><br><span class="line">            <span class="comment">// 撤回</span></span><br><span class="line">            socket.on(<span class="string">'recallMessage'</span>, data =&gt; &#123; <span class="built_in">console</span>.log(<span class="string">'recall'</span>, data) &#125;)</span><br><span class="line">            socket.on(<span class="string">'connect'</span>, () =&gt; &#123; <span class="built_in">console</span>.log(<span class="string">'1. 连接success'</span>) &#125;)</span><br><span class="line">            socket.on(<span class="string">'reconnect'</span>, attemptNumber =&gt; &#123; <span class="built_in">console</span>.log(<span class="string">'5. SOCKET正在重连'</span>, attemptNumber) &#125;)</span><br><span class="line">            socket.on(<span class="string">'reconnect_attempt'</span>, () =&gt; &#123; <span class="built_in">console</span>.log(<span class="string">'6. SOCKET正在重连'</span>) &#125;)</span><br><span class="line">            socket.on(<span class="string">'connect_error'</span>, err =&gt; &#123; <span class="built_in">console</span>.log(<span class="string">'2. 连接fail.'</span>, err) &#125;)</span><br><span class="line">            socket.on(<span class="string">'connect_timeout'</span>, err =&gt; &#123; <span class="built_in">console</span>.log(<span class="string">'3. 连接timeout.'</span>, err) &#125;)</span><br><span class="line">            socket.on(<span class="string">'disconnect'</span>, reason =&gt; &#123; <span class="built_in">console</span>.log(<span class="string">'4. 连接断开.'</span>, reason) &#125;)</span><br><span class="line">            socket.on(<span class="string">'reconnect_failed'</span>, () =&gt; &#123; <span class="built_in">console</span>.log(<span class="string">'6. SOCKET重连失败'</span>) &#125;)</span><br><span class="line">            socket.on(<span class="string">'error'</span>, err =&gt; &#123; <span class="built_in">console</span>.log(<span class="string">'SOCKET连接错误'</span>) &#125;)</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="comment">// 断开socket</span></span><br><span class="line">        socketStop () &#123;</span><br><span class="line">          <span class="keyword">if</span> (<span class="keyword">this</span>.socket) &#123;</span><br><span class="line">            <span class="keyword">this</span>.socket.close()</span><br><span class="line">            <span class="keyword">this</span>.socket = <span class="literal">null</span></span><br><span class="line">          &#125;</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="comment">// 发送消息，触发的是服务端的事件</span></span><br><span class="line">        sendMessage (sendMsg) &#123;</span><br><span class="line">          <span class="keyword">this</span>.socket.emit(<span class="string">'message'</span>, sendMsg);</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="comment">// 撤回消息，触发的是服务端的事件</span></span><br><span class="line">        handleRecallMsg(recallMsg) &#123;</span><br><span class="line">          <span class="keyword">this</span>.socket.emit(<span class="string">'recallMessage'</span>, recallMsg)</span><br><span class="line">        &#125;,</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="3">
<li><strong>实现的功能</strong></li>
</ol>
<ul>
<li>小程序端<ul>
<li>列表中选择列表，点击进入聊天</li>
<li>支持<strong>上线</strong>、<strong>离线</strong>提示，支持离线<strong>留言</strong>，<strong>离线消息</strong>提醒</li>
<li>支持<strong>文本</strong>、<strong>图片</strong>、<strong>语音</strong>类型消息，消息支持<strong>撤回</strong>，撤回提示</li>
<li>支持下拉页面加载<strong>历史消息</strong></li>
<li>支持全屏<strong>预览图片</strong></li>
</ul>
</li>
</ul>
<ol start="4">
<li><strong>实现效果</strong></li>
</ol>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="https://i.loli.net/2019/10/15/bAiF7LkcVyruCdP.png" alt="im-weclient.png" title="">
                </div>
                <div class="image-caption">im-weclient.png</div>
            </figure>
<p>别吐槽了，没有<code>ui</code>图，我已经尽力了，我知道很丑0.0…</p>
<p><img src="https://i.loli.net/2019/10/15/hndSFIZOvLlY4a2.png" alt="old-luo.png" style="zoom:150%;"></p>
<ol start="5">
<li><strong>注意的地方</strong></li>
</ol>
<ul>
<li>小程序端发送<strong>语音</strong>是通过<strong>小程序录音</strong>与<strong>音频播放</strong>来实现，过程中注意录音权限的获取与<strong>拒绝</strong>情况的处理。首次请求录音权限，用户拒绝之后不会再次调起授权框，此时需弹框让用户点击<strong>设置</strong>按钮，进入到微信小程序的<strong>设置页面</strong>手动打开授权</li>
<li>录音过程与微信的发语音过程类似（当然体验没那么好啦），<strong>按住说话</strong>，<strong>上滑取消发送</strong>，<strong>录音少于 1 秒不发送提示</strong>等，实现是参考的一篇文章，但是找不到原文的地址了，故在此贴一下我的代码（参考），待我找到了原文再贴上来</li>
<li>图片预览则是微信的图片预览<code>api</code>，遍历消息列表中的所有图片消息即可</li>
<li>长按弹出<strong>撤回</strong>菜单，需做个全屏遮罩，点击空白处隐藏撤回菜单</li>
<li>文本输入发送时，我会将消息添加至消息列表中，然后在滚动页面到最底部，但是此时因为输入框仍然拥有焦点（光标闪烁），页面滚动会将输入框也往上带，导致<strong>输入框错位</strong>。这是微信小程序中的<code>bug</code>，官方建议在<code>input</code>框聚焦的时候<strong>避免执行动画</strong>。在参考其他的聊天应用时，解决方法是在发送文本消息时，直接让输入框失焦，简单粗暴，直接收起了键盘，也就是每发送一条消息，就得收起一次键盘，用户得重新点击输入框聚焦弹起键盘。个人觉得体验比输入框错位更操蛋，就没有采用这样的方式，但暂时也没有好的方式避免错位的情况。o(╥﹏╥)o~~</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span><br><span class="line">  onLoad() &#123;</span><br><span class="line">    <span class="keyword">this</span>.initRecord() <span class="comment">// 录音</span></span><br><span class="line">    <span class="keyword">this</span>.initAudio() <span class="comment">// 音频播放</span></span><br><span class="line">  &#125;</span><br><span class="line">  methods: &#123;</span><br><span class="line">    <span class="comment">// 初始化录音管理</span></span><br><span class="line">	initRecord () &#123;</span><br><span class="line">      <span class="keyword">this</span>.recordManager = wx.getRecorderManager()</span><br><span class="line">      <span class="comment">// 录音结束事件</span></span><br><span class="line">      <span class="keyword">this</span>.recordManager.onStop(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">// 通过 sendLock 标志来判断是否需要发送</span></span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">this</span>.sendLock) &#123;</span><br><span class="line">          <span class="comment">// 上锁不发送</span></span><br><span class="line">          wx.showToast(&#123;</span><br><span class="line">            title: <span class="string">'已取消发送'</span>, <span class="comment">//提示的内容,</span></span><br><span class="line">            icon: <span class="string">'none'</span>, <span class="comment">//图标,</span></span><br><span class="line">            duration: <span class="number">2000</span>, <span class="comment">//延迟时间,</span></span><br><span class="line">          &#125;);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">          <span class="keyword">if</span> (res.duration &lt; <span class="number">1000</span>) &#123;</span><br><span class="line">            wx.showToast(&#123;</span><br><span class="line">              title: <span class="string">'录音时间太短'</span>,</span><br><span class="line">              icon: <span class="string">'none'</span>,</span><br><span class="line">              duration: <span class="number">2000</span>,</span><br><span class="line">            &#125;);</span><br><span class="line">          &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">'录音文件：'</span>, res)</span><br><span class="line">            <span class="keyword">this</span>.sendAudio(res)</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;);</span><br><span class="line">      <span class="comment">// 录音开始事件</span></span><br><span class="line">      <span class="keyword">this</span>.recordManager.onStart(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'监听录音事件开始：'</span>)</span><br><span class="line">        wx.showToast(&#123;</span><br><span class="line">          title: <span class="string">'正在录音...'</span>, <span class="comment">//提示的内容,</span></span><br><span class="line">          icon: <span class="string">'none'</span>, <span class="comment">//图标,</span></span><br><span class="line">          duration: <span class="number">60000</span>, <span class="comment">//延迟时间,</span></span><br><span class="line">        &#125;);</span><br><span class="line">        <span class="keyword">this</span>.sendLock = <span class="literal">false</span> <span class="comment">// 解锁</span></span><br><span class="line">      &#125;)</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment">// 长按开始录音</span></span><br><span class="line">    handleRecordStart (e) &#123;</span><br><span class="line">      <span class="keyword">this</span>.startPoint = e.touches[<span class="number">0</span>] <span class="comment">// 记录手指位置</span></span><br><span class="line">      <span class="keyword">this</span>.recordManager.start(&#123; <span class="attr">duration</span>: <span class="number">60000</span>, <span class="attr">format</span>: <span class="string">'mp3'</span> &#125;) <span class="comment">// 开始录音</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment">// 结束录音</span></span><br><span class="line">    handleRecordStop () &#123;</span><br><span class="line">      wx.hideToast() <span class="comment">// 隐藏toast提示框</span></span><br><span class="line">      <span class="keyword">this</span>.recordManager.stop() <span class="comment">// 停止录音</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment">// 上滑取消发送</span></span><br><span class="line">    handleTouchMove (e) &#123;</span><br><span class="line">      <span class="comment">//touchmove时触发</span></span><br><span class="line">      <span class="keyword">var</span> moveLenght = e.touches[e.touches.length - <span class="number">1</span>].clientY - <span class="keyword">this</span>.startPoint.clientY; <span class="comment">//移动距离</span></span><br><span class="line">      <span class="keyword">if</span> (<span class="built_in">Math</span>.abs(moveLenght) &gt; <span class="number">50</span>) &#123;</span><br><span class="line">        wx.showToast(&#123;</span><br><span class="line">          title: <span class="string">"松开手指,取消发送"</span>,</span><br><span class="line">          icon: <span class="string">"none"</span>,</span><br><span class="line">          duration: <span class="number">60000</span></span><br><span class="line">        &#125;);</span><br><span class="line">        <span class="keyword">this</span>.sendLock = <span class="literal">true</span>;<span class="comment">//触发了上滑取消发送，上锁</span></span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        wx.showToast(&#123;</span><br><span class="line">          title: <span class="string">"正在录音，上划取消发送"</span>,</span><br><span class="line">          icon: <span class="string">"none"</span>,</span><br><span class="line">          duration: <span class="number">60000</span></span><br><span class="line">        &#125;);</span><br><span class="line">        <span class="keyword">this</span>.sendLock = <span class="literal">false</span>;<span class="comment">//上划距离不足，依然可以发送，不上锁</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 初始化音频管理   </span></span><br><span class="line">    initAudio () &#123;</span><br><span class="line">      <span class="keyword">this</span>.innerAudio &amp;&amp; <span class="keyword">this</span>.innerAudio.destroy()</span><br><span class="line">      <span class="keyword">this</span>.innerAudio = wx.createInnerAudioContext()</span><br><span class="line">      <span class="keyword">this</span>.innerAudio.onEnded(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'end audio...'</span>)</span><br><span class="line">        <span class="comment">// 停止所有动画</span></span><br><span class="line">        <span class="keyword">this</span>.chatList.forEach(<span class="function"><span class="params">item</span> =&gt;</span> &#123;</span><br><span class="line">          <span class="keyword">this</span>.$set(item, <span class="string">'isPlay'</span>, <span class="literal">false</span>)</span><br><span class="line">        &#125;)</span><br><span class="line">      &#125;)</span><br><span class="line">      <span class="keyword">this</span>.innerAudio.onPlay(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'play audio...'</span>)</span><br><span class="line">      &#125;)</span><br><span class="line">      <span class="keyword">this</span>.innerAudio.onStop(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'stop audio...'</span>)</span><br><span class="line">      &#125;)</span><br><span class="line">      <span class="keyword">this</span>.innerAudio.onError(<span class="function">(<span class="params">err</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(err)</span><br><span class="line">        <span class="keyword">const</span> msg = &#123;</span><br><span class="line">          <span class="string">'10001'</span>: <span class="string">'系统错误'</span>,</span><br><span class="line">          <span class="string">'10002'</span>: <span class="string">'网络错误'</span>,</span><br><span class="line">          <span class="string">'10003'</span>: <span class="string">'文件错误'</span>,</span><br><span class="line">          <span class="string">'10004'</span>: <span class="string">'格式错误'</span>,</span><br><span class="line">          <span class="string">'-1'</span>: <span class="string">'未知错误'</span></span><br><span class="line">        &#125;</span><br><span class="line">        wx.showToast(&#123;</span><br><span class="line">          title: msg[err.errCode],</span><br><span class="line">          icon: <span class="string">'none'</span>,</span><br><span class="line">          duration: <span class="number">2000</span></span><br><span class="line">        &#125;);</span><br><span class="line">      &#125;)</span><br><span class="line"></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment">// 播放录音</span></span><br><span class="line">    playAudio (item) &#123;</span><br><span class="line">      <span class="comment">// 如果当前在播放则停止</span></span><br><span class="line">      <span class="keyword">if</span> (item.isPlay) &#123;</span><br><span class="line">        <span class="keyword">this</span>.innerAudio.stop()</span><br><span class="line">        <span class="keyword">this</span>.$set(item, <span class="string">'isPlay'</span>, <span class="literal">false</span>)</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">// 停止所有动画</span></span><br><span class="line">      <span class="keyword">this</span>.chatList.forEach(<span class="function"><span class="params">item</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">this</span>.$set(item, <span class="string">'isPlay'</span>, <span class="literal">false</span>)</span><br><span class="line">      &#125;)</span><br><span class="line">      <span class="keyword">this</span>.innerAudio.src = item.content <span class="comment">// 音频地址</span></span><br><span class="line">      <span class="keyword">this</span>.$set(item, <span class="string">'isPlay'</span>, <span class="literal">true</span>) <span class="comment">// 开始播放动画</span></span><br><span class="line">      <span class="keyword">this</span>.innerAudio.play() <span class="comment">// 播放</span></span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="最后"><a href="#最后" class="headerlink" title="最后"></a>最后</h3><p>客户需求：过两天演示用，能不能把微信视频通话接到小程序里面，只是加个链接过去就可以了吧。</p>
<p>我：我…<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="https://i.loli.net/2019/12/11/hl2qgjcYNZJyKwF.gif" alt="fzjg.gif" title="">
                </div>
                <div class="image-caption">fzjg.gif</div>
            </figure></p>

        </div>

        <blockquote class="post-copyright">
    
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2019-12-11T02:38:33.971Z" itemprop="dateUpdated">2019-12-11 10:38:33</time>
</span><br>


        
        关于学习类文章网上已经有非常多，而此处文章都是我在学习过程中整理摘录的笔记，参考文章可以点击文末的参考链接进行查阅
        
    </div>
    
    <footer>
        <a href="https://lafen.gitee.io">
            <img src="/img/avatar.jpg" alt="lafen">
            lafen
        </a>
    </footer>
</blockquote>

        
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;" class="page-reward-btn waves-effect waves-circle waves-light">赏</a>
</div>



        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/mpvue/">mpvue</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/socket-io/">socket.io</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/vue/">vue</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=https://lafen.gitee.io/2019/10/15/mpvue-vue-socketio使用实现即时通讯/mpvue-vue-socketio使用实现即时通讯/&title=《mpvue-vue-socketio使用实现即时通讯》 — lafen&pic=https://lafen.gitee.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=https://lafen.gitee.io/2019/10/15/mpvue-vue-socketio使用实现即时通讯/mpvue-vue-socketio使用实现即时通讯/&title=《mpvue-vue-socketio使用实现即时通讯》 — lafen&source=lafen's personal blog" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https://lafen.gitee.io/2019/10/15/mpvue-vue-socketio使用实现即时通讯/mpvue-vue-socketio使用实现即时通讯/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《mpvue-vue-socketio使用实现即时通讯》 — lafen&url=https://lafen.gitee.io/2019/10/15/mpvue-vue-socketio使用实现即时通讯/mpvue-vue-socketio使用实现即时通讯/&via=https://lafen.gitee.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=https://lafen.gitee.io/2019/10/15/mpvue-vue-socketio使用实现即时通讯/mpvue-vue-socketio使用实现即时通讯/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/2019/11/17/js-数组与递归思想/js-数组与递归思想/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">js-数组与递归思想</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/2019/09/27/js-宏任务和微任务/js-宏任务和微任务/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">js-宏任务和微任务</h4>
      </a>
    </div>
  
</nav>



    




















</article>

<div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
        <i class="icon icon-quote-left"></i>
        打笔巨款？~
        <i class="icon icon-quote-right"></i>
    </h3>
    <div class="reward-content">
        
        <div class="reward-code">
            <img id="rewardCode" src="/img/wechat.jpg" alt="打赏二维码">
        </div>
        
        <label class="reward-toggle">
            <input id="rewardToggle" type="checkbox" class="reward-toggle-check" data-wechat="/img/wechat.jpg" data-alipay="/img/alipay.jpg">
            <div class="reward-toggle-ctrol">
                <span class="reward-toggle-item wechat">微信</span>
                <span class="reward-toggle-label"></span>
                <span class="reward-toggle-item alipay">支付宝</span>
            </div>
        </label>
        
    </div>
</div>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style="display:none">
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style="display:none">
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            
                <span><a href="/atom.xml" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            
            <span>博客内容遵循 <a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">知识共享 署名 - 非商业性 - 相同方式共享 4.0 国际协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p><span>lafen &copy; 2019 - 2020</span>
            <span>
                
                Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://github.com/yscoder/hexo-theme-indigo" target="_blank">indigo</a>
            </span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=https://lafen.gitee.io/2019/10/15/mpvue-vue-socketio使用实现即时通讯/mpvue-vue-socketio使用实现即时通讯/&title=《mpvue-vue-socketio使用实现即时通讯》 — lafen&pic=https://lafen.gitee.io/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=https://lafen.gitee.io/2019/10/15/mpvue-vue-socketio使用实现即时通讯/mpvue-vue-socketio使用实现即时通讯/&title=《mpvue-vue-socketio使用实现即时通讯》 — lafen&source=lafen's personal blog" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https://lafen.gitee.io/2019/10/15/mpvue-vue-socketio使用实现即时通讯/mpvue-vue-socketio使用实现即时通讯/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《mpvue-vue-socketio使用实现即时通讯》 — lafen&url=https://lafen.gitee.io/2019/10/15/mpvue-vue-socketio使用实现即时通讯/mpvue-vue-socketio使用实现即时通讯/&via=https://lafen.gitee.io" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=https://lafen.gitee.io/2019/10/15/mpvue-vue-socketio使用实现即时通讯/mpvue-vue-socketio使用实现即时通讯/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: true };


</script>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/main.min.js"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/search.min.js" async></script>






<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



<script>
(function() {
    var OriginTitile = document.title, titleTime;
    document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
            document.title = '死鬼去哪里了！';
            clearTimeout(titleTime);
        } else {
            document.title = '(つェ⊂)咦!又好了!';
            titleTime = setTimeout(function() {
                document.title = OriginTitile;
            },2000);
        }
    });
})();
</script>



<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"scale":1,"jsonPath":"/live2dw/assets/shizuku.model.json"},"display":{"positon":"right","width":150,"height":300},"mobile":{"show":true,"scale":0.8},"react":{"opacity":0.8,"opacityDefault":0.8,"opacityOnHover":0.6},"log":false});</script></body>
</html>
